<?php
//by willson 105328468@qq.com 2014/10/13
//member module interface

class coupon extends core {
	private $coupon_mod;
	
	public function __construct() {
		parent::__construct();
		$this->coupon_mod = m("coupon");
	}

	//我的优惠券列表
	//-2过期，-1已使用，0无效，1正常
	public function index() {
		$this->_set_expired();
        if (!$this->member_id) script('请先登录账号', 'wap.php?tpl=login');
		$where = " cs.member_id='{$this->member_id}' AND cs.member_id>'0'";
		$status = isset($_GET['status']) ? $_GET['status'] : '';
		$offset = (isset($_GET['offset']) && trim($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && trim($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		if ($status != '') {
			//失效：包括过期和已使用的
			$status = intval($status);
			if ($status==0) {
				$where .= " AND cs.status<='0'";
			} else {
				$where .= " AND cs.status='{$status}'";
			}
		}
		if (isMobile()){
            $sql = "SELECT cs.*, c.name, c.type, c.begin_time, c.end_time, c.min_price, c.permit_goods, c.handy_time
			FROM {$this->tbp}coupon_sn cs LEFT JOIN {$this->tbp}coupon c ON cs.coupon_id=c.id
			WHERE {$where} ORDER BY cs.id DESC LIMIT {$offset},{$pagesize}";
            $coupons = $this->db->get_results($sql);
        }else{
		    $coupons = SQL::share('coupon_sn cs')->left('coupon c', 'cs.coupon_id=c.id')->where($where)->order('cs.id DESC')
                ->limit($offset, $pagesize)->isezr()->find('cs.*, c.name, c.type, c.begin_time, c.end_time, c.min_price, c.permit_goods, c.handy_time');
        }
        $nav = '';

		if ($coupons) {
            $nav = $this->ezr->get_navigation();
			foreach ($coupons as $k=>$coupon) {
				$coupons[$k]->begin_time = $coupon->begin_time>0 ? date("Y-m-d", $coupon->begin_time) : '0';
				$coupons[$k]->end_time = $coupon->end_time>0 ? date("Y-m-d", $coupon->end_time) : '0';
                //计算获得天数后到期的时间
                if ($coupon->handy_time>0){
                    $handy_time = $coupon->get_time + $coupon->handy_time * 24*60*60;
                    $coupons[$k]->end_time = date("Y-m-d", $handy_time);
                }

				$coupons[$k]->coupon_money = intval($coupon->coupon_money);
				if (intval($coupon->min_price)) {
					$min_price = intval($coupon->min_price);
					$coupons[$k]->min_price_memo = "满{$min_price}元即可使用";
				} else {
					$coupons[$k]->min_price_memo = "无门槛";
				}
				if ($coupon->permit_goods) {
					$coupons[$k]->memo = "（部分市区可用）";
				} else {
					$coupons[$k]->memo = "（全场通用）";
				}
			}
			$coupons = add_domain_deep($coupons, array("pic"));
		}

        //增加PC需要的内容
        if (!isMobile()){
            //头像
            $sql = "SELECT avatar FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $avatar = $this->db->get_row($sql);
            //名称
            $sql = "SELECT nick_name FROM {$this->tbp}member WHERE id='{$this->member_id}'";
            $nick_name = $this->db->get_row($sql);
                success(array('coupons'=>$coupons, 'avatar'=>$avatar , 'nick_name'=>$nick_name, 'page'=>$nav));
            }else{
                success($coupons);
            }

	}

	//优惠券列表(不是我的优惠券)
	public function coupon_list() {
		$type = (isset($_GET['type']) && intval($_GET['type'])) ? intval($_GET['type']) : 1;
		$offset = (isset($_GET['offset']) && intval($_GET['offset'])) ? intval($_GET['offset']) : 0;
		$pagesize = (isset($_GET['pagesize']) && intval($_GET['pagesize'])) ? intval($_GET['pagesize']) : 8;
		$sql = "SELECT * FROM {$this->tbp}coupon WHERE type='{$type}' ORDER BY id DESC LIMIT {$offset},{$pagesize}";
		$coupons = $this->db->get_results($sql);
		if ($coupons) {
			foreach ($coupons as $k=>$coupon) {
				$coupons[$k]->begin_time = $coupon->begin_time>0 ? date("Y-m-d", $coupon->begin_time) : '0';
				$coupons[$k]->end_time = $coupon->end_time>0 ? date("Y-m-d", $coupon->end_time) : '0';
				$coupons[$k]->coupon_money = intval($coupon->coupon_money);
				if (intval($coupon->min_price)) {
					$min_price = intval($coupon->min_price);
					$coupons[$k]->min_price_memo = "满{$min_price}元即可使用";
				} else {
					$coupons[$k]->min_price_memo = "无门槛";
				}
				if ($coupon->permit_goods) {
					$coupons[$k]->memo = "（部分商品可用）";
				} else {
					$coupons[$k]->memo = "（全场通用）";
				}
				$sql = "SELECT count(*) FROM {$this->tbp}coupon_sn WHERE coupon_id='{$coupon->id}'";
				$coupons[$k]->quantity = intval($this->db->get_var($sql));
				$sql = "SELECT count(*) FROM {$this->tbp}coupon_sn WHERE coupon_id='{$coupon->id}' AND member_id!=0";
				$coupons[$k]->persons = intval($this->db->get_var($sql));
			}
		}
	    success($coupons);
	}

	public function course(){
	    success('ok');
    }

	//优惠券详情，可用在html5页面
	public function detail() {
		$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
		$sql = "SELECT *, '' as goods FROM {$this->tbp}coupon WHERE id='{$id}'";
		$coupon = $this->db->get_row($sql);
		if ($coupon) {
			if ($coupon->permit_goods==1) {
				$goods_ids = $this->coupon_mod->get_coupon_goods($id);
				if ($goods_ids) {
					$goods_ids = implode(",", $goods_ids);
					$sql = "SELECT id, name FROM {$this->tbp}goods WHERE id IN ($goods_ids)";
					$goods = $this->db->get_results($sql);
					$coupon->goods = $goods;
				}
			}
		}
		success($coupon);
	}


	//领取优惠券
	public function ling() {
		if (!$this->member_id) error('请登录', -100);
		$coupon_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
		if ($coupon_id<=0) error('数据错误');
		$result = $this->coupon_mod->send($coupon_id, $this->member_id);
		switch ($result) {
			case 1:success('ok');break;
			case 0:error('领取优惠券失败');break;
			case -1:error('你已经领取了该优惠券');break;
			case -2:error('该优惠券不存在');break;
		}
		/*
		$sql = "SELECT * FROM {$this->tbp}coupon WHERE id='{$coupon_id}'";
		$coupon = $this->db->get_row($sql);
		if ($coupon) {
			$num_per_person = $coupon->num_per_person;
			if ($num_per_person) {
				$sql = "SELECT COUNT(*) FROM {$this->tbp}coupon_sn WHERE member_id='{$this->member_id}' AND coupon_id='{$coupon_id}'";
				$num = intval($this->db->get_var($sql));
				if ($num>=$num_per_person) {
					error('你已经领取了该优惠券');
				} else {
					if ($coupon_id>1) {
						if ($this->_ling($coupon_id)) {
							success("ok");
						}
					} else { //新人优惠券
        				$sn = date('m') . date('d') . substr(time(), -3) . substr(microtime(), 2, 6) .rand(100, 999);
						$sql = "INSERT INTO {$this->tbp}coupon_sn (coupon_id, coupon_money, sn, member_id, add_time, get_time, status) VALUES
							('{$coupon_id}', '".$coupon->coupon_money."', '{$sn}', '{$this->member_id}', '".time()."', '".time()."', '1')";
						$this->db->query($sql);
						success("ok");
					}
				}
			//优惠券没有限制领取数量
			} else {
				if ($this->_ling($coupon_id)) {
					success("ok");
				}
			}
		}
		*/
		error('领取优惠券失败');
	}

	//领取优惠券，先判断优惠券是否有效
	private function _ling($coupon_id) {
		$sql = "SELECT MIN(cs.id) FROM {$this->tbp}coupon_sn cs INNER JOIN {$this->tbp}coupon c ON cs.coupon_id=c.id
			WHERE coupon_id='{$coupon_id}' AND cs.status='1' AND c.status='1' AND cs.member_id='0'";
		$coupon_sn_id = intval($this->db->get_var($sql));
		if ($coupon_sn_id) {
			$sql = "UPDATE {$this->tbp}coupon_sn SET member_id='{$this->member_id}', get_time='".time()."' WHERE id='{$coupon_sn_id}'";
			//echo $sql;
			$ok = $this->db->query($sql);
			if ($ok) {
				return true;
			}
		}
		return false;
	}


	//手工添加优惠券
	public function add() {
		$sn = isset($_POST['sn']) ? trim($_POST['sn']) : '';
		if ($sn) {
			$sql = "SELECT id FROM {$this->tbp}coupon_sn WHERE sn='{$sn}' AND member_id='0'";
			$id = intval($this->db->get_var($sql));
			if ($id) {
				$sql = "UPDATE {$this->tbp}coupon_sn SET member_id='{$this->member_id}', get_time='".time()."' WHERE id='{$id}'";
				$this->db->query($sql);
				success("ok");
			} else {
				error("优惠券码不正确");
			}
		}
	}

	//设置过期的优惠券
	private function _set_expired() {
		$now = time();
		$sql = "SELECT cs.id, c.name, c.begin_time, c.end_time
			FROM {$this->tbp}coupon_sn cs INNER JOIN {$this->tbp}coupon c ON cs.coupon_id=c.id
			WHERE cs.member_id='{$this->member_id}' AND c.end_time<'{$now}' AND c.end_time>'0' AND cs.status=1";
		$coupons = $this->db->get_results($sql);

		if ($coupons) {
			$ids = '';
			foreach ($coupons as $key => $coupon) {
				if ($ids) {
					$ids .= ", {$coupon->id}";
				} else {
					$ids = "{$coupon->id}";
				}
			}
			if ($ids) {
				$sql = "UPDATE {$this->tbp}coupon_sn SET status='-2' WHERE member_id='{$this->member_id}' AND id IN ($ids)";
				$this->db->query($sql);
			}
		}

        //查询获取后几天到期的优惠券
        $c = SQL::share('coupon')->where("handy_time>0")->find();
        if ($c){
            $total = array();
            foreach ($c as $k => $g){
                $cs = SQL::share('coupon_sn sn')->left('coupon c', 'c.id=sn.coupon_id')
                    ->where("sn.member_id='{$this->member_id}' AND sn.coupon_id='{$g->id}' AND sn.status=1")
                    ->find('sn.*, c.handy_time');
                if (!empty($cs)){
                    $total = array_merge($cs, $total);
                }
            }

            //设置过期优惠券
            if (count($total)>0){
                foreach ($total as $k => $g){
                    $handy_time = $g->get_time + $g->handy_time * 24*60*60;
                    if ($handy_time < $now){
                        SQL::share('coupon_sn')->where("member_id='{$this->member_id}' AND id='{$g->id}'")->update(array('status'=>-2));
                    }
                }
            }
        }
	}
}